package tau.dimes.ipGeo;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import tau.dimes.config.ipGeo.IpGeoProvider;
import tau.dimes.data.Column;
import tau.dimes.data.Row;
import tau.dimes.data.Table;
import tau.dimes.data.TableException;
import tau.dimes.db.Database;
import tau.dimes.db.DatabaseException;
import tau.dimes.db.DatabaseFactory;
import tau.dimes.util.IPHelper;

public class IpGeoProviderImpl
{
	private final IpGeoProvider provider;

	public IpGeoProviderImpl(IpGeoProvider provider)
	{
		this.provider = provider;
	}

	public void translate(Table table, int ipColumn, String latitudeColumnName,
		String longitudeColumnName) throws DatabaseException, IpGeoException, TableException
	{
		try
		{
			Database database = DatabaseFactory.create(provider.getServer());
			PreparedStatement ps = database.getPreparedStatement(provider.getSql());
			int pCount = ps.getParameterMetaData().getParameterCount();
			Vector<String> latitudeColumn = new Vector<String>();
			Vector<String> longitudeColumn = new Vector<String>();
			for (Row row : table.rows())
			{
				String ip = IPHelper.toNumericalString(row.get(ipColumn));
				for (int i = 1; i <= pCount; i++)
					ps.setString(i, ip);
				ResultSet rs = ps.executeQuery();
				if (rs.next())
				{
					latitudeColumn.add(rs.getString(provider.getLatitudeColumn()));
					longitudeColumn.add(rs.getString(provider.getLongitudeColumn()));
				}
				else
				{
					latitudeColumn.add("0");
					longitudeColumn.add("0");
				}
				rs.close();
			}

			table.addColumn(new Column(latitudeColumnName), latitudeColumn);
			table.addColumn(new Column(longitudeColumnName), longitudeColumn);
		}
		catch (SQLException e)
		{
			throw new IpGeoException(e);
		}
	}
}
